package com.hebeiboruan.common.uitl;
import com.hebeiboruan.common.exception.CommonException;
import com.hebeiboruan.common.exception.ServiceResultEnum;
import com.hebeiboruan.common.exception.system.user.UserException;
import com.hebeiboruan.common.exception.system.user.UserResultEnum;
import io.jsonwebtoken.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
 * jwt工具类
 *
 * @author 一支枯木
 * @date 2023/11/5
 */

public class JwtUtils {
    private static final String RSA_PUBLIC_KEY = "123u90i09dejldkn!ek!@#!@$lwr$@hpw@!#!@jaoi@!#$vjd#@gth@!#ih43p[20][,.,xzc;'21-=3!@Y@!$^@";
    public static String getJWTTokenRsa(Claims claims){
        String JwtToken = Jwts.builder()
                .setClaims(claims)
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000*60*60*12))
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, RSA_PUBLIC_KEY)
                .compact();
        System.out.println(JwtToken);
        return JwtToken;
    }
    public static Integer getUserNo(HttpServletRequest request){
        return decodeRsa(request).get("userNo",Integer.class);
    }
    public static Claims decodeRsa(HttpServletRequest request){
        String token=request.getHeader("Token");
        if (token == null) {
            return null;
        }

        try{
            JwtParser parser = Jwts.parser();
            parser.setSigningKey(RSA_PUBLIC_KEY);

            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            JwsHeader header = claimsJws.getHeader();

            if (claimsJws != null) {
                return claimsJws.getBody();
            }else {
                return null;
            }
        }catch (ExpiredJwtException e){
            throw new UserException(UserResultEnum.LOGIN_STATE_ERROR);
        }


    }
}
